import React, { PureComponent, Fragment } from 'react';
import { Tabs, Row, Typography, Col, message, Button, Popover, Icon, Select, Form } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import _ from 'lodash';
import moment from 'moment';
import { showConfirm } from '@/utils/utils';
import * as utils from '../../utils/treeUtils';
import * as api from '@/services/SupplyPlanMgr';
import Btns from '@/components/Btns';

const FormItem = Form.Item;
const { TabPane } = Tabs;
const { Option } = Select;

@connect(state => ({
  versions: state.OperatingPlanVersions.data,
  searchItems: state.SupplyPlanItems.searchItems,
  all: state.SupplyPlanItems.all,
}))
@Form.create()
export default class PageTop extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      expandForm: false,
      loading: false,
      group: '',
      batch: '',
      // build: '',
      product: '',
      productType: '',
    };
  }

  componentWillReceiveProps(nextProps) {
    // match变动
    const { setFieldsValue } = this.props.form;
    if (this.props.match.params.version !== nextProps.match.params.version) {
      const { dispatch } = this.props;
      setFieldsValue({ group: '', batch: '', productType: '', product: '', build: '' });
      dispatch({
        type: 'SupplyPlanItems/clear',
      });
      this.setState({
        group: '',
        expandForm: false,
        batch: '',
        // build: '',
        product: '',
        productType: '',
      });
    }
  }

  // 根据查询条件搜索
  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = _.values(
        _.mapValues(fieldsValue, value => (value ? value.split('|')[1] : 'null')),
      ).join('/');
      this.props.getItems(this.props, values);
    });
  };

  // 重置查询条件
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.setState({
      group: '',
      batch: '',
      // build: '',
      product: '',
      productType: '',
    });
  };

  // 切换搜索条件的展示方式
  handleScreenBtn = () => {
    const self = this;
    this.setState({
      expandForm: !self.state.expandForm,
    });
    this.props.expandForm(!self.state.expandForm);
  };

  // 1、月度动态版：
  // 规则： {归属月份}月动态版{版本号}-{最后更新时间}
  // 示例：201910月动态版V1-20191201；
  // 2、投资版、战规版、大定价版：
  // 规则：{版本类型}{版本号}-{最后更新时间}
  // 示例：投资版V1-20191102，战规版V3-20191102，大定价版V2-20191102
  // 3、预算版：
  // 规则：{预算年份}{全年/年中}预算版{版本号}-{最后更新时间}
  // 示例：2019全年预算版V1-20181212，2019全年预算版V5-20190331，
  // 2019年中预算版V1-20190501，2019年中预算版V5-20190831
  // 4、审批通过后才显示最后更新时间，过程中不显示（显示状态）；
  buildPlanVersionName = versionInfo => {
    if (versionInfo.versionType === 'dynamic') {
      return `${versionInfo.affiliationMonth}月动态版${versionInfo.versionNum}-${versionInfo.lastDate}`;
    }
    if (versionInfo.versionType === 'budget') {
      return `${versionInfo.versionTypeName}${versionInfo.versionNum}-${versionInfo.lastDate}`;
    }
    if (
      versionInfo.versionType === 'investment' ||
      versionInfo.versionType === 'strategy' ||
      versionInfo.versionType === 'pricing'
    ) {
      return `${versionInfo.versionTypeName}${versionInfo.versionNum}-${versionInfo.lastDate} ${
        versionInfo.isAssessmentVersion * 1 === 1 ? '(考核版)' : ''
      }`;
    }
    return '';
  };

  buildPriceVersionName = versionInfo => {
    if (versionInfo.priceVersionType === 'dynamic') {
      return `${
        versionInfo.priceAscriptionDate
          ? moment(versionInfo.priceAscriptionDate).format('YYYYMM')
          : ''
      }月动态版${versionInfo.priceVersionNum}-${versionInfo.priceLastDate}`;
    }
    if (
      versionInfo.priceVersionType === 'investment' ||
      versionInfo.priceVersionType === 'strategy' ||
      versionInfo.priceVersionType === 'pricing'
    ) {
      return `${versionInfo.priceVersionTypeName}${versionInfo.priceVersionNum}-${
        versionInfo.priceLastDate
      } ${versionInfo.priceIsAssessmentVersion * 1 === 1 ? '(考核版)' : ''}`;
    }
    return '';
  };

  // 搜索条件的展示方式———展开
  renderAdvancedForm = () => {
    const { getFieldDecorator, setFieldsValue } = this.props.form;
    const { searchItems, all } = this.props;
    const { group, product, productType, batch } = this.state;
    // 组团
    let groups = [];
    let batchs = [];
    let products = [];
    let productTypes = [];
    let builds = [];
    // 批次
    batchs = utils.getSearchTypeItems(searchItems.org_batch, 'name', 'id');
    // 组团
    groups = utils.getSearchTypeItems(searchItems.org_group, 'name', 'id');
    // 业态
    products = utils.getSearchTypeItems(searchItems.org_product, 'name', 'id');
    // 产品构成
    productTypes = utils.getSearchTypeItems(
      searchItems.org_product,
      'proProductName',
      'proProductCode',
    );
    // 楼栋
    builds = utils.getSearchTypeItems(searchItems.org_build, 'name', 'id');
    if (batch) {
      // 有组团 取当前组团所有业态产品构成 否 取所有批次下所有业态产品构成
      let orgStage = [];
      orgStage = _.filter(searchItems.org_batch, { id: batch });
      // if (!batch && all) {
      //   orgStage = _.filter(all, { name: orgStage[0].name });
      //   console.log(orgStage)
      // }
      products = utils.getSearchSeltetItems(orgStage, 'org_product', 'name', 'id');
      productTypes = utils.getSearchSeltetItems(
        orgStage,
        'org_product',
        'proProductName',
        'proProductCode',
      );
      builds = utils.getSearchSeltetItems(orgStage, 'org_build', 'name', 'id');
    }
    if (group) {
      let orgStage = [];
      orgStage = _.filter(searchItems.org_group, { id: group });
      batchs = utils.getSearchSeltetItems(orgStage, 'org_batch', 'name', 'id');
      products = utils.getSearchSeltetItems(orgStage, 'org_product', 'name', 'id');
      productTypes = utils.getSearchSeltetItems(
        orgStage,
        'org_product',
        'proProductName',
        'proProductCode',
      );
      builds = utils.getSearchSeltetItems(orgStage, 'org_build', 'name', 'id');
    }

    if (productType) {
      let orgProduct = [];
      let orgBatch = [];
      if (group) {
        const orgGroup = _.filter(searchItems.org_group, { id: group });
        orgProduct = orgGroup[0].children;
      } else if (batch) {
        orgBatch = _.filter(searchItems.org_batch, { id: batch });
        const allGroup = [];
        orgProduct = utils.buildChildren(allGroup, orgBatch, 'org_product');
      } else {
        orgProduct = searchItems.org_product;
      }
      orgBatch = _.filter(orgProduct, { proProductCode: productType });
      products = utils.getSearchSeltetItems(orgBatch, 'org_product', 'name', 'id');
      builds = utils.getSearchSeltetItems(orgBatch, 'org_build', 'name', 'id');
    }
    if (product) {
      let orgProduct = [];
      let orgBatch = [];
      if (group) {
        const orgGroup = _.filter(searchItems.org_group, { id: group });
        orgProduct = orgGroup[0].children;
      } else if (batch) {
        orgBatch = _.filter(searchItems.org_stage, { id: batch });
        const allGroup = [];
        orgProduct = utils.buildChildren(allGroup, orgBatch, 'org_product');
      } else {
        orgProduct = searchItems.org_product;
      }
      if (group === '' && batch === '') {
        const productName = _.filter(searchItems.org_product, { id: product });
        orgProduct = _.filter(searchItems.org_product, { name: productName[0].name });
      } else {
        orgProduct = _.filter(orgProduct, { id: product });
      }
      builds = utils.getSearchSeltetItems(orgProduct, 'org_build', 'name', 'id');
    }

    return (
      <Form layout="inline" onSubmit={this.handleSearch} className="form">
        <Row type="flex" justify="center" align="middle">
          <Col md={21} sm={24}>
            <FormItem label="组团">
              {getFieldDecorator(
                'group',
                {},
              )(
                <Select
                  size="small"
                  dropdownMatchSelectWidth={false}
                  placeholder="全部"
                  style={{ width: 180 }}
                  onChange={value => {
                    setFieldsValue({ batch: '', productType: '', product: '', build: '' });
                    this.setState({
                      group: value.split('|')[0],
                      batch: '',
                      productType: '',
                      product: '',
                      // build: '',
                    });
                  }}
                >
                  <Option value="">全部</Option>
                  {groups &&
                    groups.length > 0 &&
                    groups.map(value => (
                      <Option key={value.code} value={`${value.code}|${value.name}`}>
                        {value.name || '暂无名称'}
                      </Option>
                    ))}
                </Select>,
              )}
            </FormItem>
            {batchs.length ? (
              <FormItem label="批次">
                {getFieldDecorator(
                  'batch',
                  {},
                )(
                  <Select
                    dropdownMatchSelectWidth={false}
                    style={{ width: 180 }}
                    onChange={value => {
                      setFieldsValue({ productType: '', product: '', build: '' });
                      this.setState({
                        batch: value.split('|')[0],
                        productType: '',
                        product: '',
                        // build: '',
                      });
                    }}
                    size="small"
                    placeholder="全部"
                  >
                    <Option value="">全部</Option>
                    {batchs &&
                      batchs.length > 0 &&
                      batchs.map(value => (
                        <Option key={value.code} value={`${value.code}|${value.name}`}>
                          {value.name || '暂无名称'}
                        </Option>
                      ))}
                  </Select>,
                )}
              </FormItem>
            ) : null}
            <FormItem label="业态">
              {getFieldDecorator(
                'productType',
                {},
              )(
                <Select
                  dropdownMatchSelectWidth={false}
                  style={{ width: 180 }}
                  size="small"
                  onChange={value => {
                    setFieldsValue({ build: '', product: '' });
                    this.setState({
                      productType: value.split('|')[0],
                      product: '',
                      // build: '',
                    });
                  }}
                  placeholder="全部"
                >
                  <Option value="">全部</Option>
                  {productTypes &&
                    productTypes.length > 0 &&
                    productTypes.map(value => (
                      <Option key={value.code} value={`${value.code}|${value.name}`}>
                        {value.name || '暂无名称'}
                      </Option>
                    ))}
                </Select>,
              )}
            </FormItem>
            <FormItem label="产品构成">
              {getFieldDecorator(
                'product',
                {},
              )(
                <Select
                  dropdownMatchSelectWidth={false}
                  style={{ width: 180 }}
                  size="small"
                  onChange={value => {
                    setFieldsValue({ build: '' });
                    this.setState({
                      product: value.split('|')[0],
                      // build: '',
                    });
                  }}
                  placeholder="全部"
                >
                  <Option value="">全部</Option>
                  {products &&
                    products.length > 0 &&
                    products.map(value => (
                      <Option key={value.code} value={`${value.code}|${value.name}`}>
                        {value.name || '暂无名称'}
                      </Option>
                    ))}
                </Select>,
              )}
            </FormItem>
            {builds.length ? (
              <FormItem label="楼栋">
                {getFieldDecorator(
                  'build',
                  {},
                )(
                  <Select
                    dropdownMatchSelectWidth={false}
                    style={{ width: 180 }}
                    // onChange={value => {
                    //   this.setState({
                    //     build: value.split('|')[0],
                    //   });
                    // }}
                    size="small"
                    placeholder="全部"
                  >
                    <Option value="">全部</Option>
                    {builds &&
                      builds.length > 0 &&
                      builds.map(value => (
                        <Option key={value.code} value={`${value.code}|${value.name}`}>
                          {value.name || '暂无名称'}
                        </Option>
                      ))}
                  </Select>,
                )}
              </FormItem>
            ) : null}
          </Col>
          <Col justify="space-around" align="middle">
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
          </Col>
        </Row>
      </Form>
    );
  };

  // nav 切换改变状态
  handleTabChange = (key, params) => {
    router.push(
      `/OperatingPlan/SupplyPlan/${params.level1}/${params.level2}/${params.project}/${params.stage}/${key}`,
    );
    this.setState({
      expandForm: false,
    });
  };

  // 版本详情
  editionDetail = versionDetail => (
    <Fragment>
      <div style={{ margin: '0 0 10px 0' }}>
        <h4>基本信息</h4>
        <Row type="flex" justify="space-between" style={{ width: '500px' }} gutter={[0, 5]}>
          <Col span={13}>
            <span>{`版本名称 : ${this.buildPlanVersionName(versionDetail)}`}</span>
          </Col>
          <Col span={11}>
            <span>{`创建人 : ${versionDetail.createBy}`}</span>
          </Col>
          <Col span={13}>
            <span>{`创建时间 : ${moment(versionDetail.createTime).format(
              'YYYY-MM-DD HH:mm:ss',
            )}`}</span>
          </Col>
          <Col span={11}>
            <span>
              {/* 创建方式 :{versionDetail.createBy === 'budget' ? '手动创建' : '自动创建'} */}
              创建方式: 系统生成
            </span>
          </Col>
          {versionDetail.updateTime ? (
            <Col span={24}>
              <span>{`更新时间 : ${moment(versionDetail.updateTime).format(
                'YYYY-MM-DD HH:mm:ss',
              )}`}</span>
            </Col>
          ) : null}
        </Row>
      </div>
      <div style={{ margin: '0 0 10px 0' }}>
        <h4>取数信息</h4>
        <Row type="flex" justify="space-between" gutter={[0, 5]}>
          {versionDetail.priceVersionType ? (
            <Col span={13}>
              <span>{`基于货值版本 : ${this.buildPriceVersionName(versionDetail)}`}</span>
            </Col>
          ) : null}
          {versionDetail.buildplanVersionName ? (
            <Col span={11}>
              <span>{`楼栋计划版本 : ${versionDetail.buildplanVersionName}`}</span>
            </Col>
          ) : null}
        </Row>
      </div>
    </Fragment>
  );

  // 按钮
  buildBtnsList = (versions, params, expandForm) => {
    const BtnsList = [];
    const { category, stage } = params;
    // if (category === 'budget') {
    //   BtnsList.push({
    //     authority: `supply_${category}_addVersion`,
    //     value: '创建新版本',
    //     btnAttribute: {
    //       loading: this.state.loading,
    //       type: 'primary',
    //       onClick: () => {
    //         const self = this;
    //         self.setState({
    //           loading: true,
    //         });
    //         api.isExistBudgetVersionUsingGET({ params: { projectFid: stage } }).then(data => {
    //           self.setState({
    //             loading: false,
    //           });
    //           if (data.data === false) {
    //             showConfirm(
    //               () => self.props.handleCreateEdition(stage),
    //               '确认创建新的预算版吗？',
    //               // '将从最新审批通过的签约计划版本创建。',
    //             );
    //           } else if (data.data === true) {
    //             showConfirm(
    //               () => self.props.handleCreateEdition(stage),
    //               `${data ? '当前分期已存在预算版，' : ''}确认创建新的预算版吗？`,
    //               // '将从最新审批通过的签约计划版本创建。',
    //             );
    //           }
    //         });
    //       },
    //     },
    //   });
    // }
    if (versions && versions.length > 0) {
      BtnsList.push({
        value: '高级筛选',
        afterIcon: expandForm ? 'up' : 'down',
        btnAttribute: {
          onClick: this.handleScreenBtn,
        },
      });
      if (category === 'investment' && versions[0].isAssessmentVersion * 1 === 0) {
        BtnsList.unshift({
          authority: 'supply_setVersionAssessment',
          value: '设为考核版',
          btnAttribute: {
            className: 'red-button',
            onClick: () => this.props.setVersionAssessment(params),
          },
        });
      }
    }

    return BtnsList;
  };

  render() {
    const { params } = this.props.match;
    const activeKey = params.category;
    const { versions } = this.props;
    const { expandForm } = this.state;
    let currentState = [];
    if (versions.length > 0 && params.version) {
      currentState = _.filter(versions, { versionId: params.version });
    }
    const BtnsList = this.buildBtnsList(currentState, params, expandForm);
    return (
      <Fragment>
        <Tabs
          activeKey={activeKey}
          animated={false}
          size="large"
          onChange={key => this.handleTabChange(key, params)}
        >
          <TabPane tab="月度动态版" key="dynamic"></TabPane>
          <TabPane tab="预算版" key="budget"></TabPane>
          <TabPane tab="战规版" key="strategy"></TabPane>
          <TabPane tab="投资版" key="investment"></TabPane>
        </Tabs>
        <Row type="flex" justify="space-between" align="middle">
          <Col className="version-selecter">
            {versions.length && currentState.length ? (
              <Row type="flex" justify="space-between" align="middle">
                <Col>
                  <Select
                    onChange={value => {
                      router.replace(
                        `/OperatingPlan/SupplyPlan/${params.level1}/${params.level2}/${params.project}/${params.stage}/${params.category}/${value}`,
                      );
                    }}
                    size="small"
                    className="version-select"
                    dropdownMatchSelectWidth={false}
                    value={currentState[0].versionId}
                  >
                    {versions.map(val => (
                      <Option key={val.versionId} value={val.versionId}>
                        {this.buildPlanVersionName(val)}
                      </Option>
                    ))}
                  </Select>
                </Col>
                <Col>
                  <Popover
                    content={currentState ? this.editionDetail(currentState[0]) : null}
                    title="版本信息"
                    trigger="hover"
                    placement="bottomLeft"
                  >
                    <Button style={{ color: '#4f84ff', border: 'solid 1px #fff' }}>
                      <Icon
                        type="snippets"
                        style={{
                          color: '#fff',
                          background: 'rgba(255, 141, 26, 1)',
                        }}
                      />
                    </Button>
                  </Popover>
                </Col>
              </Row>
            ) : null}
          </Col>

          <Col>
            <Btns
              rowAttribute={{
                type: 'flex',
                justify: 'space-between',
                align: 'middle',
                gutter: [5, 0],
              }}
              BtnsList={BtnsList}
            />
          </Col>
        </Row>
        {expandForm ? this.renderAdvancedForm() : null}
      </Fragment>
    );
  }
}
